<?php
require '../private/data/data.php';

session_start();
$isLogin = isset($_SESSION['user']) ? true : false;
$user = isset($_SESSION['user']) ? $_SESSION['user'] : null;

$hasError = isset($_SESSION['has_error']) ? $_SESSION['has_error'] : false;
$errorBag = isset($_SESSION['error_bag']) ? $_SESSION['error_bag'] : ['content' => ''];

if (isset($_SESSION['has_error']) && isset($_SESSION['error_bag'])) {
	unset($_SESSION['has_error']);
	unset($_SESSION['error_bag']);
}

$sql = 'select * from `messages` order by created_at desc';
$data = query($sql);

?>

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>message board</title>
	<link rel="stylesheet" type="text/css" href="css/message_board.css">
</head>
<body>
	<div id="wholePage">
		<form method="post" <?php if($isLogin): ?> action="../private/action/logout_action.php" <?php else: ?> action="register.php?op=2" <?php endif; ?> class="isLogin">
			<div>
				<a href="#">
					<img src="img/Backham.png">
					<p><?php if ($isLogin) echo $user['user_name'] ?></p>
					<input type="submit" <?php if($isLogin): ?> value="logout" <?php else: ?> value="login" <?php endif; ?> class="quit">
				</a>
			</div>
		</form>
		<form method="post" action="../private/action/post_message.php" class="message">
			<textarea name="content" rows="7" cols="54" placeholder="Please enter message content"></textarea>
			<div style="height: 15px; font-size: 14px; color: red; text-align: center;">
				<?php if ($hasError) echo $errorBag['content'] ?>
			</div>
			<input type="submit" value="submit" class="submit">
		</form>
		<?php foreach ($data as $message): ?>
		<div class="message">
			<a href="#">
				<img src="img/Backham.png">
			</a>
			<div class="content">
				<span><a href="#"><?= $message['user_name'] ?></a>&nbsp;: </span>
				<span class="message"><?= $message['content'] ?></span>
			</div>
			<div class="something">
			<span class="time"><?= $message['created_at'] ?></span>
			<ul>
			<?php if ($user['user_name'] == $message['user_name']): ?>
				<li><a href="../private/action/delete_message.php?id=<?= $message['id'] ?>">delete</a></li>
			<?php endif; ?>
				<li><a href="#">reply</a></li>
				<li>|</li>
				<li><a href="../private/action/praise_action.php?id=<?= $message['id'] ?>">praise&nbsp;(<?= $message['like_num'] ?>)</a></li>
			</ul>
			</div>
		</div>
		<?php endforeach; ?>
	</div>
</body>
</html>